# coding=utf-8
from flask import Flask, request,make_response,render_template, redirect, url_for,escape
from werkzeug.utils import secure_filename # 使用这个是为了确保filename是安全的
from os import path
from function import getscore
from function import randomcolor
import requests
import base64
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片


app = Flask(__name__)


def log_request(req:"flask_request",res:str,other):     
    with open("view.log","a") as log:
        print(req,res,other,file=log,sep='|')





@app.route("/upload",methods=['GET','POST'])
def upload():
    # global file_name
    # file_name=""
    if request.method=='POST':
        f = request.files["file"]
        base_path = path.abspath(path.dirname(__file__))
        upload_path = path.join(base_path,'static/')
        file_name = upload_path + secure_filename(f.filename)
        f.save(file_name)
        imgname = 'static\\'+secure_filename(f.filename)
        url = secure_filename(f.filename)

        result = getscore(imgname)
        col =randomcolor()
        log_request(request,result,col)
        return render_template('upload.html',the_imgname= url,the_result=result,col=col)
        return redirect(url_for('upload'))
        
    return render_template('upload.html')


@app.route('/viewlog')
def view_the_log() -> 'html':
   
    contents = []
    with open('view.log') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))

    titles =('from','score','color')

        
    return render_template('viewlog.html',
                            the_title='View Log',
                            the_row_titles=titles,
                            the_data=contents,)

    

if __name__ == '__main__':
    app.run(debug=True)
   


